package cn.zzszxyy.hr.service;

import cn.zzszxyy.hr.comm.CryptUtil;
import cn.zzszxyy.hr.comm.Global;
import cn.zzszxyy.hr.comm.StringUtil;
import cn.zzszxyy.hr.model.DepartmentEntity;
import cn.zzszxyy.hr.model.UserEntity;
import cn.zzszxyy.hr.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 作者:张伟
 * <p>
 * 联系:adamzzww@163.com
 * 时间:2016-11-27
 * 说明:用户管理
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<UserEntity> findByUserNameLike(String userName, int pageIndex, int pageSize) {
        PageRequest pageRequest = new PageRequest(--pageIndex, pageSize);
        return userRepository.findByUserNameLike(userName, pageRequest);
    }

    public Page<UserEntity> findByUserName(String userName, int pageIndex, int pageSize) {
        PageRequest pageRequest = new PageRequest(--pageIndex, pageSize);
        Page<UserEntity> userList = null;
        if (StringUtil.isEmpty(userName)) {
            userList = userRepository.findAll(pageRequest);
        } else {
            userList = userRepository.findByUserName(userName, pageRequest);
        }
        return userList;
    }

    public List<String> getAllUserName() {
        return userRepository.getAllUserName();
    }

    public UserEntity findOne(int id) {
        return userRepository.findOne(id);
    }

    public UserEntity save(UserEntity userEntity) {
        userEntity.setCreateTime(new Date());
        return userRepository.save(userEntity);
    }

    public UserEntity findByLoginNameAndUserPwd(String loginName, String userPwd) {
        String encript_pwd = CryptUtil.getInstance().defalutEncrypt(userPwd);
        List<UserEntity> list = userRepository.findByLoginNameAndUserPwd(loginName, encript_pwd);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public int restUserPwdFor(int userId) {
        String restPwd = CryptUtil.getInstance().defalutEncrypt(Global.DEFALUT_PWD);
        return userRepository.restUserPwdFor(restPwd, userId);
    }

    public int changeUserPwdFor(String userPwd, int userId) {
        return userRepository.changeUserPwdFor(CryptUtil.getInstance().defalutEncrypt(userPwd), userId);
    }

    public boolean isExistByLoginName(String loginName) {
        return userRepository.findByLoginName(loginName).size() > 0;
    }

}
